import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import newtext as htmltext
import logging

class CourseInfo(db.Model):
	id=db.StringProperty()
	email=db.StringProperty()


class Handler(webapp.RequestHandler):
	def get(self):
		fed_identity=self.request.get("openid_identifier")
		self.response.out.write(fed_identity)
	def post(self):
		fed_identity=self.request.get("openid_identifier")
#		logging.info("redirecting to: %s"%users.create_login_url(federated_identity=fed_identity,dest_url="/register"))
#		self.response.out.write(fed_identity)
		self.redirect(users.create_login_url(federated_identity=fed_identity,dest_url="/register"))

class Register(webapp.RequestHandler):
	def get(self):
		student=users.get_current_user()	
		if student:
			if student.email():
				html=htmltext.full
			
				res=db.GqlQuery("SELECT * FROM CourseInfo WHERE email = '%s'"%student.email())
				existing=[i.id for i in res]
				
				sub=[]
				for i in range(6):
					sub.append("")
					for val in htmltext.allcourses[i]:
						if val.upper() in existing:
							sub[i]+="""<div style="float:left"><input type="checkbox" name="courses" value="%s" CHECKED>%s</input></div>"""%(val.upper(),val)
						else:
							sub[i]+="""<div style="float:left"><input type="checkbox" name="courses" value="%s">%s</input></div>"""%(val.upper(),val)
				sub=[users.get_current_user().email(),users.create_logout_url(dest_url=self.request.uri)]+sub			
				html=html%(tuple(sub))
				self.response.out.write(html)
			else:
				subst="<span style=\"color:red\">%s</span> didn't provide any email address. Please select another OpenID provider below.<br><br>"%student.federated_provider()
				self.response.out.write(htmltext.basic%(subst+htmltext.openid_box))

		else:
			self.response.out.write(htmltext.basic%htmltext.openid_box)

	def post(self):
		student=users.get_current_user()	
		if student:
			courses=self.request.get("courses",allow_multiple=True)
			res=db.GqlQuery("SELECT * FROM CourseInfo WHERE email = '%s'"%student.email())
			existing=[i.id for i in res]
			for course in courses:
				if not course in existing:
					new=CourseInfo()
					new.email=student.email()
					new.id=course.upper()
					new.put()
				else:
					pass

			for course in res:
				if not course.id in courses:
					db.delete(course)
				else:
					pass
	

			self.response.out.write("""
			<h2>Registration complete</h2>
			<a href="/register">Modify</a> your details.
			""")
		
		else:

			self.redirect(users.create_login_url(federated_identity="gmail.com",dest_url=self.request.uri))

application = webapp.WSGIApplication([('/register', Register),('/handler', Handler),('/', Register)])

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()

